/*Copyright (C) 2009 - 2011 MASSART GAUTHIER and Careil Baptiste

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "../headers.h"

#ifdef WIN32
#include <windows.h>
#include <Wincrypt.h>

unsigned char *MD5(PBYTE d, unsigned long n, unsigned char *md) {
	HCRYPTPROV hProv = 0;
	HCRYPTHASH hHash = 0;
	DWORD cbHash = MD5_DIGEST_LENGHT;

	CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
	CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
	CryptHashData(hHash, d, n, 0);
	CryptGetHashParam(hHash, HP_HASHVAL, md, &cbHash, 0);
	CryptDestroyHash(hHash);
	CryptReleaseContext(hProv, 0);

	return md;
}
#endif

char to_hex_ch(unsigned char c) {
	c &= 0xF;
	if(c >= 10)
		return c + 'a' - 10;
	return c + '0';
}

void convert_md5_to_ascii(char ascii[33], unsigned char md[MD5_DIGEST_LENGHT]) {
	unsigned char	c;
	size_t	i;

	for(i = 0; i < 32; i++) {
		c = md[i / 2];
		if(i % 2 == 0)
			c >>= 4;
		ascii[i] = to_hex_ch(c);
	}
	ascii[i] = '\0';
}

short get_md5_file(char *nom_fichier, char ascii[33]) {
	char  *buffer_file = NULL;
	unsigned char md5[MD5_DIGEST_LENGHT];
	short len = 0;
#ifdef WIN32
	HCRYPTPROV hProv = 0;
	HCRYPTHASH hHash = 0;
	DWORD cbHash = MD5_DIGEST_LENGHT;
#else
	MD5_CTX context;
#endif
	FILE *file = fopen(nom_fichier, "rb");

	if(file != NULL) {
		buffer_file = malloc(1000 * sizeof(*buffer_file));
		memset(buffer_file, 0, sizeof(buffer_file));

#ifdef WIN32
		CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
		CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);
#else
		MD5_Init(&context);
#endif

		while((len = fread(buffer_file, 1, 1000, file)) > 0) {
#ifdef WIN32
			CryptHashData(hHash, buffer_file, len, 0);
#else
			MD5_Update(&context, buffer_file, len);
#endif
		}

#ifdef WIN32
		CryptGetHashParam(hHash, HP_HASHVAL, md5, &cbHash, 0);
		CryptDestroyHash(hHash);
		CryptReleaseContext(hProv, 0);
#else
		MD5_Final(md5, &context);
#endif

		convert_md5_to_ascii(ascii, md5);
		fclose(file);
		free(buffer_file);
	}
	else {
		return 1;
	}

	return 0;
}
